package com.iscas.lndicatormonitor.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iscas.lndicatormonitor.common.CustomResult;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MongoClient mongoClient;
    @PostMapping("/upload-yaml")
    public CustomResult uploadYaml(@RequestParam("yamlFile") MultipartFile yamlFile) throws Exception {
        // 读取上传的YAML文件
        byte[] yamlBytes = yamlFile.getBytes();
        String yamlContent = new String(yamlBytes);

        // 连接到MongoDB
        MongoDatabase database = mongoClient.getDatabase("efficientTest");
        MongoCollection<Document> collection = database.getCollection("microDefinition");

        // 将YAML文本内容直接插入MongoDB
        Document document = new Document("content", yamlContent);
        collection.insertOne(document);

        // 获取插入文档的ID
        ObjectId id = (ObjectId) document.get("_id");

        String _id = id.toHexString();
        return CustomResult.ok(_id);
    }


    @PostMapping("/upload-apifile")
    public CustomResult uploadAPI(@RequestParam("jsonFile") MultipartFile jsonFile) throws Exception{

        // 读取上传的JSON文件内容
        byte[] jsonBytes = jsonFile.getBytes();
        String jsonContent = new String(jsonBytes);

        // 连接到MongoDB
        MongoDatabase database = mongoClient.getDatabase("efficientTest");
        MongoCollection<Document> collection = database.getCollection("apiDoc");

        // 将JSON数据插入MongoDB
        Document document = new Document("content", jsonContent);
        collection.insertOne(document);

        // 获取插入文档的ID
        ObjectId id = (ObjectId) document.get("_id");

        String _id = id.toHexString();

        return CustomResult.ok(_id);
    }
}
